package com.mbc.hr.manager;

import java.sql.SQLException;
import java.util.List;

import com.mbc.common.entities.SystemProperty;
import com.mbc.common.exception.DataDuplicationException;
import com.mbc.common.exception.ForeignConflictException;
import com.mbc.common.manager.AbstractMgr;
import com.mbc.common.param.CriteriaParams;
import com.mbc.common.utils.KeyGenerator;
import com.mbc.hr.data.LeaveSetupDataList;
import com.mbc.hr.entities.LeaveType;

public class LeaveSetupMgr extends AbstractMgr {
	
	public LeaveSetupMgr(){}
	
	public LeaveSetupMgr(String sessionId){
		this.sessionId = sessionId;
	}
	
	public void create(LeaveType leaveSetup)throws Exception{
		openConnection();
		try {
			beginTransaction();
			leaveSetup.setLeaveTypeID(KeyGenerator.generateKey(entityManager));
			entityManager.persist(leaveSetup);
			if(leaveSetup.isCalendarDefault()){
				SystemProperty l_SysProp = entityManager.find(SystemProperty.class, "calendar_leave");
				if(l_SysProp != null){
					l_SysProp.setValue(String.valueOf(leaveSetup.getLeaveTypeID()));
					entityManager.merge(l_SysProp);
				}
				else{
					l_SysProp = new SystemProperty();
					l_SysProp.setKey("calendar_leave");
					l_SysProp.setValue(String.valueOf(leaveSetup.getLeaveTypeID()));
					entityManager.persist(l_SysProp);
				}
			}
			commitTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			if(DataDuplicationException.isUniqueKyeError(e))
				throw new DataDuplicationException(e.getMessage());
			else
				throw e;
		} finally {
			closeConnection();
		}
	}
	
	public void update(LeaveType leaveSetup)throws Exception{
		openConnection();
		try {
			beginTransaction();
			entityManager.merge(leaveSetup);
			if(leaveSetup.isCalendarDefault()){
				SystemProperty l_SysProp = entityManager.find(SystemProperty.class, "calendar_leave");
				if(l_SysProp != null){
					l_SysProp.setValue(String.valueOf(leaveSetup.getLeaveTypeID()));
					entityManager.merge(l_SysProp);
				}
				else{
					l_SysProp = new SystemProperty();
					l_SysProp.setKey("calendar_leave");
					l_SysProp.setValue(String.valueOf(leaveSetup.getLeaveTypeID()));
					entityManager.persist(l_SysProp);
				}
			}
			commitTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public void delete(long leaveTypeID)throws Exception{
		openConnection();
		try {
			beginTransaction();
			LeaveType l_leaveType = entityManager.find(LeaveType.class, leaveTypeID);
			entityManager.remove(l_leaveType);
			commitTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			if(e.getCause().getCause().getCause() instanceof SQLException){
				if(ForeignConflictException.FOREIGN_CONFLICT_ERROR_CODE == ((SQLException)e.getCause().getCause().getCause()).getErrorCode())
					throw new ForeignConflictException(e);
				else
					throw e;
			}
			else
				throw e;
		} finally {
			closeConnection();
		}
	}
	
	public LeaveType find(long leaveTypeID)throws Exception{
		openConnection();
		try {
			return entityManager.find(LeaveType.class, leaveTypeID);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public List<LeaveType> findAll()throws Exception{
		openConnection();
		try {
			return entityManager.createNamedQuery("LeaveType.findAll", LeaveType.class).getResultList();
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public LeaveSetupDataList findLeaveSetups(CriteriaParams cri) throws Exception{
		openConnection();
		try {
            String l_jpql = "select lt from LeaveType lt where lt.name like '%" + cri.getKeyword() + "%'";
            
            List<LeaveType> l_entityList = entityManager.createQuery(l_jpql, LeaveType.class)
                    .setFirstResult(cri.getIndex())
                    .setMaxResults(cri.getSize())
                    .getResultList();
            
            LeaveSetupDataList l_dataList = new LeaveSetupDataList();
            l_dataList.setEntityList(l_entityList);
            
            if(cri.getIndex() == 0){
            	String l_countQuery = "select count(lt.name) from LeaveType lt where lt.name like '%" + cri.getKeyword() + "%'";
            	l_dataList.setTotalRecord(Long.parseLong(entityManager.createQuery(l_countQuery).getSingleResult().toString()));
            }
			return l_dataList;
		} catch (Exception e) {
			throw e;
		} finally{
			closeConnection();
		}	
	}
}
